<template>
  <el-dialog :title="currentTitle" :visible.sync="dialogVisible" width="42%">
    <el-tabs tab-position="top" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="预警图表" name="1">
        <div class="alarm-page">
          <el-row class="search-bar">
            <el-col :gutter="10" :span="6">
              <el-date-picker
                v-model="queryParamsInner.reportDay"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-col>

            <el-col :span="6" :offset="2">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
              >
                搜索
              </el-button>
            </el-col>
          </el-row>

          <div class="alarmform">
            <h3>预警图</h3>
            <div
              id="alarmChart"
              style="width: 720px; height: 300px"
              class="alarmPlaceholder"
            ></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="音 频" name="2">
        <div class="audio-page">
          <!-- 顶部日期选择 + 搜索区域 -->
          <el-row class="search-bar">
            <el-col :gutter="10" :span="6">
              <el-date-picker
                v-model="queryParamsInner.reportDay"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-col>

            <el-col :span="6" :offset="2">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
              >
                搜索
              </el-button>
            </el-col>
          </el-row>
          <!-- 波形图区域（这里用占位，实际可结合 audio 标签 + 可视化库实现） -->
          <div class="waveform">
            <!-- 模拟波形显示，实际可替换为 audio 可视化 -->
            <div class="waveformPlaceholder">
              <!-- <av-bars audio-src="/images/test.wav"> </av-bars> -->
              <av-waveform 
               ref="audioRef"
               v-if="flag"
                :playtime-with-ms="true"
                :canv-width="660"
                :audio-src="audioSrcUrl"
              ></av-waveform>
            </div>
          </div>

          <div class="spectrum">
            <h3>频谱图</h3>
            <div
              id="spectrumChart"
              style="width: 720px; height: 300px"
              class="spectrumPlaceholder"
            ></div>
          </div>
        </div>
      </el-tab-pane>
      <!--流程流转记录-->
      <el-tab-pane label="设备信息" name="3">
        <el-form ref="formRef" label-width="130px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备编号" prop="deviceNum">
                <el-input
                  readonly
                  v-model="currentTerminal.deviceNum"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备经度" prop="longitude">
                <el-input
                  readonly
                  v-model="currentTerminal.longitude"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="设备纬度" prop="latitude">
                <el-input
                  readonly
                  v-model="currentTerminal.latitude"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属区域" prop="region">
                <el-input
                  readonly
                  v-model="currentTerminal.region"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="安装时间" prop="installTime">
                <el-input
                  readonly
                  v-model="currentTerminal.installTime"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安装位置" prop="installPosition">
                <el-input
                  readonly
                  v-model="currentTerminal.installPosition"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="基准噪声值" prop="noiseReference">
                <el-input
                  readonly
                  v-model="currentTerminal.noiseReference"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <span slot="footer" class="dialog-footer">
      <el-button type="danger" @click="dialogVisible = false">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as echarts from "echarts";
import moment from "moment";
import { getInfoExtend } from "@/api/leakage/fileVideo";

require("echarts/theme/macarons"); // echarts theme
import { formatDateTime } from "@/utils/ruoyi";

export default {
  name: "LeakDetectionDetailDialog",
  data() {
    return {
      flag : true,
      baseAudioUrl: process.env.VUE_APP_BASE_API + "/common/minio/download",
      audioSrcUrl:"",

      foo: null,
      formRef: null,
      queryParamsInner: {
        deviceNum: null,
        reportDay: null,
      },
      currentTitle: "",
      dialogVisible: false,
      terminalHisDataList: [],
      terminalHisPageDataList: [],
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      pager: {
        pageNum: 1,
        pageSize: 15,
      },
      // terminalDataChart: undefined,
      currentTerminal: {
        deviceNum: null,
        longitude: null,
        latitude: null,
        region: null,
        installTime: null,
        installPosition: null,
        noiseReference: null,
      },
      activeName: "1",
      seriesData: [],

      deviceChartWave: undefined,

      optionWave: {
        title: {
          text: "音频频谱图",
          left: "left",
        },
        legend: {},
        tooltip: {
          // 鼠标悬浮触发事件
          trigger: "axis", // 鼠标悬浮会有竖线
          // triggerOn: 'click', // 触发方式是点击，默认是none悬浮 实现全图表点击，可以用点击tooltip实现
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "cross",
            // 默认为直线，可选为：'line' | 'shadow | cross'
            crossStyle: {
              color: "red", // cross横线的颜色
            },
            label: {
              // backgroundColor : 'red' // 上图显示的颜色
              backgroundColor: "#5184F7", // 上图显示的颜色 type 使用 cross 能出现一个很炫酷的十字交叉
            },
          },

          formatter(params) {
            let result = "";
            params.forEach(function (item) {
              // ${item.marker} 是小圆点
              result += `${item.marker}频率：${item.value.frequency}Hz<br>${item.marker}功率：${item.value.amplitude}dbm`; // 更改悬浮显示 通过加入 <br> 实现换行
            });
            return result;
          },
          extraCssText: "width:150px; white-space:pre-wrap", // 定义悬浮框的宽度以及换行
        },
        toolbox: {
          show: true,

          feature: {
            saveAsImage: {},
            //  restore: {},
            magicType: {
              type: ["line", "bar"],
            },
            dataView: {
              show: true,
              title: "数据视图",
              lang: ["数据视图", "关闭", "刷新"],
            },
          },
        },

        dataset: {
          // 这里指定了维度名的顺序，从而可以利用默认的维度到坐标轴的映射。
          // 如果不指定 dimensions，也可以通过指定 series.encode 完成映射，参见后文。
          dimensions: ["frequency", "amplitude"],
          source: [
            //   {"frequency" : 0.6103515625,"amplitude" : 28.4566404739284}
            //  ,{"frequency" : 1.8310546875,"amplitude" : 16.0276307227271}
            //  ,{"frequency" : 3.0517578125,"amplitude" : 25.3161639906202}
          ],
        },
        xAxis: {
          type: "category",
          name: "频率（Hz）",
        },
        yAxis: {
          type: "value",
          name: "振幅",
        },
        series: [
          {
            name: "频谱数据",
            type: "line", // 用折线图展示，也可用 'bar' 柱状图
            encode: {
              // x: 0,
              // y: 1,
              x: "frequency",
              y: "amplitude",
            },
            smooth: true, // 曲线平滑（可选）
            symbol: "none", // 隐藏折点（可选）
          },

          // {type: 'bar'},
          // {type: 'bar'},
          // {type: 'bar'}
        ],
      },

      colorWave: "red",
      deviceChartAlarm: undefined,
      optionAlarm: {
        title: {
          text: "预警图",
          left: "left",
        },
        legend: {},
        tooltip: {
          extraCssText: "width: 200px !important;",
          // textStyle:{
          //   width : 100,
          // },
          // 鼠标悬浮触发事件
          trigger: "axis", // 鼠标悬浮会有竖线
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "cross",
            // 默认为直线，可选为：'line' | 'shadow | cross'
            crossStyle: {
              color: "red", // cross横线的颜色
            },
            label: {
              backgroundColor: "#5184F7", // 上图显示的颜色 type 使用 cross 能出现一个很炫酷的十字交叉
            },
          },

          formatter(params) {
            let result = "";
            params.forEach(function (item) {
              // ${item.marker} 是小圆点
              result += `${item.marker}时间：${item.value.reportDay}<br>${item.marker}功率：${item.value.dbValue}dbm<br>${item.marker}预警值：${item.value.noiseReference}dbm`; // 更改悬浮显示 通过加入 <br> 实现换行
            });
            return result;
          },
          extraCssText: "width:150px; white-space:pre-wrap", // 定义悬浮框的宽度以及换行
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {},
            //  restore: {},
            magicType: {
              type: ["line", "bar"],
            },
            dataView: {
              show: true,
              title: "数据视图",
              lang: ["数据视图", "关闭", "刷新"],
            },
          },
        },

        dataset: {
          // 这里指定了维度名的顺序，从而可以利用默认的维度到坐标轴的映射。
          // 如果不指定 dimensions，也可以通过指定 series.encode 完成映射，参见后文。
          dimensions: ["reportDay", "status", "dbValue", "noiseReference"],
          source: [
            //   {"frequency" : 0.6103515625,"amplitude" : 28.4566404739284}
            //  ,{"frequency" : 1.8310546875,"amplitude" : 16.0276307227271}
            //  ,{"frequency" : 3.0517578125,"amplitude" : 25.3161639906202}
          ],
        },
        xAxis: {
          type: "category",
          name: "日期",
        },
        yAxis: {
          type: "value",
          name: "振幅",
        },
        series: [
          {
            name: "功率",
            color: "",
            type: "bar", // 用折线图展示，也可用 'bar' 柱状图
            encode: {
              // x: 0,
              // y: 1,
              x: "reportDay",
              y: "dbValue",
            },
            smooth: true, // 曲线平滑（可选）
            symbol: "none", // 隐藏折点（可选）

            markLine: {
              // symbol: ["none", "none"], // 去掉箭头
              label: {
                // show: false,
                position: "end",
                formatter: "{b}",
              },
              data: [
                {
                  name: "预警值",
                  yAxis: 16,
                },
              ],
              lineStyle: {
                // type: "solid",
                color: "#FF1D00",
                width: 1,
              },
            },
          },
        ],
      },
    };
  },
  methods: {
    handleSearch() {
      this.getData();
    },

    getColorByStatus(status) {
      if (!status) {
        return "white";
      }
      let statusColor = [
        { color: "#02a553", status: "正常" },
        { color: "#ff022f", status: "报警" },
        { color: "#d09602", status: "疑似" },
        { color: "#2556f6", status: "无数据" },
      ];
      for (let i = 0; i < statusColor.length; i++) {
        if (statusColor[i].status === status) {
          return statusColor[i].color;
        }
      }
    },

    handlePlay() {},
    handleStop() {},
    handleDownload() {},
    handleClick(tab, event) {},
    initChart() {
      this.deviceChartWave = echarts.init(
        document.getElementById("spectrumChart")
      );
      this.deviceChartWave.setOption(this.optionWave);

      this.alarmChart = echarts.init(document.getElementById("alarmChart"));
      this.alarmChart.setOption(this.optionAlarm);
    },
    getData() {
      if (!this.queryParamsInner.reportDay) {
        this.$message.error("上报日期为必选查询条件，不能为空！");
        return;
      }
      this.loading = true;
      getInfoExtend(this.queryParamsInner).then((res) => {
        this.loading = false;
        this.deviceChartWave.setOption({
          dataset: {
            source: res.data.videoSpectrum ? res.data.videoSpectrum : [], // 更新数据
          },
        });

        this.alarmChart.setOption({
          dataset: {
            source: res.data.alarmData ? [res.data.alarmData] : [], // 更新数据
          },
        });
        var _option = this.alarmChart.getOption();
        _option.series[0].color = this.getColorByStatus(
          res.data.alarmData.status
        );
        _option.series[0].markLine.data = [
          {
            yAxis: res.data.alarmData.noiseReference, // n是websocket返回要显示的值
            label: {
              position: "end", // 文字位置
              formatter: res.data.alarmData.noiseReference, //文字
            },
            lineStyle: { color: "red" },
          },
        ];

        this.alarmChart.setOption(_option);
       this.flag  = false ;
       this.$nextTick(() => { 
          this.audioSrcUrl  = this.baseAudioUrl +"?filename=" +  res.data.fileName;
          this.flag  = true ;
       });
        this.total = res.data.length;
      });
    },


    openDialog(terminal) {
      this.currentTerminal = terminal;
      this.dialogVisible = true;
      if (this.currentTerminal.deviceNum) {
        this.currentTitle = "详情" + this.currentTerminal.deviceNum;
      }
      this.queryParamsInner.reportDay = terminal.reportDay;

      this.queryParamsInner.deviceNum = terminal.deviceNum;
      this.$nextTick(() => {
        this.initChart();
        this.getData();
      });
    },
  },
  mounted() {},
};
</script>

<style scoped lang="scss">
::v-deep .el-dialog__wrapper {
  z-index: 3000 !important;
}

.audio-page {
  padding: 20px;
  background: #fff;
}
.search-bar,
.btn-group {
  margin-bottom: 16px;
}
.waveform {
  margin-bottom: 20px;
}
.waveform-placeholder {
  width: 100%;
  height: 120px;
  background: #f2f6fc;
  /* 模拟波形底色，实际可通过音频可视化库生成 */
}
.spectrum {
  margin-top: 20px;
}
.spectrum-legend {
  margin-bottom: 10px;
}
.spectrum-toolbar {
  margin-bottom: 10px;
}
.spectrum-chart-placeholder {
  width: 100%;
  height: 200px;
  background: #f9f9f9;
  /* 模拟图表区域，实际用 ECharts 等渲染 */
}
</style>
